Create Project: controller_returns_text_json (add Spring Boot Starters from the table)
Create Package: entities (inside main package)
– Create Interface: PersonEntity.java (inside package entities)
Create Package: controllers (inside main package)
– Create Class: MyController.java (inside controllers package)
PersonEntity.java
package com.ivoronline.springboot.controller_returns_text_json.entities;
public class PersonEntity {
public Integer id;
public String name;
public Integer age;
}
MyController.java
package com.ivoronline.springboot.controller_returns_text_json.controllers;
import com.ivoronline.springboot.controller_returns_text_json.entities.PersonEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class MyController {
@ResponseBody
@RequestMapping("/Hello")
public PersonEntity hello() {
//CREATE INSTANCE
PersonEntity personEntity = new PersonEntity();
personEntity.id = 1;
personEntity.name = "John";
personEntity.age = 20;
//RETURN INSTANCE AS JSON STRING
return personEntity; //{"id":1,"name":"John","age":20}
}
}